#include "ce_ui_renderer.h"
#include "../global/ce_view.h"
#include "../vulkan/ce_vulkan_manager.h"

/**
 * -1,1     0,1      1,1
 *
 * 0,-1     0,0      0,1
 *
 * -1,-1    0,-1     1,-1
 */

CE_UIRenderer::CE_UIRenderer()
{
    this->_addressId = this->_getAddressString();
    CE_VulkanManager::getInstance()->addUIObject(this->_addressId);
}
std::string CE_UIRenderer::_getAddressString()
{
    std::stringstream ss;
    ss << "CE_UISprite@0x"
       << std::hex << std::setw(sizeof(void *) * 2)
       << std::setfill('0')
       << reinterpret_cast<uintptr_t>(this);
    return ss.str();
}
/**
 * @brief 更新渲染器的着色器
 *
 * @param shaderPath 着色器路径
 */
void CE_UIRenderer::updateShader(std::string shaderPath)
{
    if (this->_shaderPath == shaderPath)
    {
        return;
    }
    this->_shaderPath = shaderPath;
    CE_VulkanManager::getInstance()->updateUIObjectShader(this->_addressId, this->_shaderPath);
}
void CE_UIRenderer::updateVertexs(float x, float y, float anchorX, float anchorY, float width, float height)
{
    
    // 计算四个角的局部坐标（相对于锚点）
    float left = -anchorX * width;
    float right = (1 - anchorX) * width;
    float bottom = -anchorY * height;
    float top = (1 - anchorY) * height;
    // 世界坐标
    float ltX = x + left;
    float ltY = y + top; // Vulkan: Y轴向下，所以 top 是更大的Y值
    float lbX = x + left;
    float lbY = y + bottom;
    float rbX = x + right;
    float rbY = y + bottom;
    float rtX = x + right;
    float rtY = y + top;

    float _ltX = (CE_View::viewWidth / 2 + ltX) / CE_View::viewWidth * 2.0 - 1.0;
    float _ltY = (CE_View::viewHeight / 2 + ltY) / CE_View::viewHeight * 2.0 - 1.0;
    //_x = (worldX / viewWidth) * 2.0f - 1.0f;     等价   _x = (worldX - viewWidth/2) /（viewWidth/2）

    float _lbX = (CE_View::viewWidth / 2 + lbX) / CE_View::viewWidth * 2.0 - 1.0;
    float _lbY = (CE_View::viewHeight / 2 + lbY) / CE_View::viewHeight * 2.0 - 1.0;

    float _rbX = (CE_View::viewWidth / 2 + rbX) / CE_View::viewWidth * 2.0 - 1.0;
    float _rbY = (CE_View::viewHeight / 2 + rbY) / CE_View::viewHeight * 2.0 - 1.0;

    float _rtX = (CE_View::viewWidth / 2 + rtX) / CE_View::viewWidth * 2.0 - 1.0;
    float _rtY = (CE_View::viewHeight / 2 + rtY) / CE_View::viewHeight * 2.0 - 1.0;

    std::vector<float> positions = {
        _ltX, _ltY, 0.0f, 0.0f, // 左上
        _lbX, _lbY, 0.0f, 0.0f, // 坐下
        _rbX, _rbY, 0.0f, 0.0f, // 右下
        _rtX, _rtY, 0.0f, 0.0f  // 右上
    };

    std::vector<int> indices = {0, 1, 2, 0, 2, 3};
    CE_VulkanManager::getInstance()->updateUIObjectVertexs(this->_addressId, positions, indices);
}

void CE_UIRenderer::updateColor(float r, float g, float b, float a)
{
    CE_VulkanManager::getInstance()->updateUIObjectColor(this->_addressId, r, g, b, a);
}
